package com.lujieni.springbootaop.aop;

import com.lujieni.springbootaop.annotation.RequestLock;
import com.lujieni.springbootaop.annotation.RequestKeyParam;
import com.lujieni.springbootaop.exception.BusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @author
 * @Title: CheckUserAspect
 * @Description:
 * @date 2022/11/22 11:02 上午
 */
@Aspect    //切面类上必须要加
@Component //必须要,否则切面类不生效
public class CheckUserAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
       定义切入点表达式 @annotation代表以带有特定注解为切入点
     */
    @Pointcut("@annotation(com.lujieni.springbootaop.annotation.RequestLock)")
    public void requestLock() {

    }

    // @Around("execution(public * * (..)) && @annotation(com.woniu.demo.annotation.RequestLock)")

    /**
     * 校验用户信息是否合法
     *
     * @param joinPoint
     * @return
     */
    @Around(value = "requestLock()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RequestLock checkUser = method.getAnnotation(RequestLock.class);
        //获取自定义key
        final String lockKey = getLockKey(joinPoint); // &lujieni&13816251641
        if(redisTemplate.opsForValue().setIfAbsent(lockKey, "1", Duration.ofSeconds(checkUser.expire()))){
            return joinPoint.proceed();
        }else{
            throw new BusinessException("100");
        }
    }

    public String getLockKey(ProceedingJoinPoint joinPoint) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        //获取连接点的方法签名对象
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //Method对象
        Method method = methodSignature.getMethod();
        //获取Method对象上的注解对象
        RequestLock requestLock = method.getAnnotation(RequestLock.class);
        //获取方法参数
        final Object[] args = joinPoint.getArgs();
        //获取Method对象上所有的注解
        final Parameter[] parameters = method.getParameters();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parameters.length; i++) {
            /*
             * 如果字段上没有加RequestKeyParam注解，则不处理
             * final RequestKeyParam keyParam = parameters[i].getAnnotation(RequestKeyParam.class);
             * 1. method.getParameters()可以获取到参数上的注解, joinPoint.getArgs()不行
             * 2. parameters[i].getType().getClassLoader() 判断是否是自定义类,classLoader等于null的时候不是自定义类
             */
            if (parameters[i].getType().getClassLoader() != null) {
                continue;
            }
            //如果属性是RequestKeyParam注解，则拼接 连接符 "& + RequestKeyParam"
            sb.append(requestLock.delimiter()).append(args[i]);
        }
        //如果方法上没有加RequestKeyParam注解
        if (StringUtils.isEmpty(sb.toString())) {
            //循环注解
            for (int i = 0; i < args.length; i++) {
                final Object object = args[i];
                //获取注解类中所有的属性字段
                final Field[] fields = object.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //判断字段上是否有RequestKeyParam注解
                    final RequestKeyParam annotation = field.getAnnotation(RequestKeyParam.class);
                    //如果没有，跳过
                    if (annotation == null) {
                        continue;
                    }
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), object.getClass());
                    //如果属性是RequestKeyParam注解，则拼接 连接符" & + RequestKeyParam"
                    sb.append(requestLock.delimiter()).append(pd.getReadMethod().invoke(object));
                }
            }
        }
        //返回指定前缀的key
        return requestLock.prefix() + sb;
    }


}
